// The W3C CSSWG provides a JSON list of all CSS properties and their status in the standard.
// See the documentation at https://www.w3.org/Style/CSS/all-properties.en.html.
//
// This script downloads that file and uses it to write an appropriately-filtered Set of property
// names to a file.

import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";

const url = "https://www.w3.org/Style/CSS/all-properties.en.json";
const outputFile = resolve("../lib/generated/allProperties.js");
const unwantedStatuses = new Set(["NOTE", "ED"]);

console.log("Downloading CSS properties...");

const res = await fetch(url);
if (res.status !== 200) {
  throw new Error(`Bad status code: ${res.status}`);
}

const rawCSSProperties = await res.json();

const propertyNames = new Set();
for (const cssProp of rawCSSProperties) {
  // Filter out properties from too-new statuses.
  // Also, '--*' needs additional logic to this module, so filter it out for now.
  if (unwantedStatuses.has(cssProp.status) || cssProp.property === "--*") {
    continue;
  }

  propertyNames.add(cssProp.property);
}

const propertyNamesJSON = JSON.stringify(Array.from(propertyNames), undefined, 2);
const dateToday = new Date();
const [dateTodayFormatted] = dateToday.toISOString().split("T");
const output = `"use strict";
// autogenerated - ${dateTodayFormatted}
// https://www.w3.org/Style/CSS/all-properties.en.html

module.exports = new Set(${propertyNamesJSON});
`;

fs.writeFileSync(outputFile, output);

// TODO: remove when we can drop Node.js 18 support and use import.meta.dirname.
function resolve(relativePath) {
  return path.resolve(path.dirname(fileURLToPath(import.meta.url)), relativePath);
}
